package com.itx.gatewayx.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itx.gatewayx.common.R;
import com.itx.gatewayx.domain.News;
import com.itx.gatewayx.service.NewsService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 新闻控制器
 *
 * @author itx
 */
@RestController
@RequestMapping("/api/news")
@RequiredArgsConstructor
public class NewsController {
    
    private final NewsService newsService;
    
    /**
     * 分页获取新闻列表
     *
     * @param current 当前页
     * @param size 每页大小
     * @param categoryId 分类ID(可选)
     * @return 新闻分页列表
     */
    @GetMapping("/list")
    public R<IPage<News>> getNewsList(
            @RequestParam(value = "current", defaultValue = "1") Long current,
            @RequestParam(value = "size", defaultValue = "10") Long size,
            @RequestParam(value = "categoryId", required = false) String categoryId) {
        IPage<News> newsPage = newsService.getNewsList(current, size, categoryId);
        return R.ok(newsPage);
    }
    
    /**
     * 获取新闻详情
     *
     * @param id 新闻ID
     * @param userId 当前用户ID(可选)
     * @return 新闻详情
     */
    @GetMapping("/detail/{id}")
    public R<News> getNewsDetail(
            @PathVariable String id,
            @RequestParam(value = "userId", required = false) Long userId) {
        News news = newsService.getNewsDetail(id, userId);
        return news != null ? R.ok(news) : R.notFound("新闻不存在");
    }
    
    /**
     * 发布新闻
     *
     * @param newsData 新闻信息，包含news和tags
     * @return 是否成功
     */
    @PostMapping
    public R<Boolean> publishNews(@RequestBody @Validated Map<String, Object> newsData) {
        News news = convertToNews(newsData);
        List<String> tags = getTagsFromData(newsData);
        
        boolean result = newsService.publishNews(news, tags);
        return result ? R.ok(true) : R.fail("发布新闻失败");
    }
    
    /**
     * 更新新闻
     *
     * @param id 新闻ID
     * @param newsData 新闻信息，包含news和tags
     * @return 是否成功
     */
    @PutMapping("/{id}")
    public R<Boolean> updateNews(
            @PathVariable String id,
            @RequestBody @Validated Map<String, Object> newsData) {
        News news = convertToNews(newsData);
        news.setUniquekey(id);
        List<String> tags = getTagsFromData(newsData);
        
        boolean result = newsService.updateNews(news, tags);
        return result ? R.ok(true) : R.fail("更新新闻失败");
    }
    
    /**
     * 删除新闻
     *
     * @param id 新闻ID
     * @param userId 用户ID
     * @return 是否成功
     */
    @DeleteMapping("/{id}")
    public R<Boolean> deleteNews(
            @PathVariable String id,
            @RequestParam("userId") Long userId) {
        boolean result = newsService.deleteNews(id, userId);
        return result ? R.ok(true) : R.fail("删除新闻失败");
    }
    
    /**
     * 点赞/取消点赞新闻
     *
     * @param newsId 新闻ID
     * @param userId 用户ID
     * @param isLike 是否点赞
     * @return 是否成功
     */
    @PostMapping("/like")
    public R<Boolean> likeNews(
            @RequestParam("newsId") String newsId,
            @RequestParam("userId") Long userId,
            @RequestParam("isLike") boolean isLike) {
        boolean result = newsService.likeNews(newsId, userId, isLike);
        return result ? R.ok(true) : R.fail("操作失败");
    }
    
    /**
     * 收藏/取消收藏新闻
     *
     * @param newsId 新闻ID
     * @param userId 用户ID
     * @param isFavorite 是否收藏
     * @return 是否成功
     */
    @PostMapping("/favorite")
    public R<Boolean> favoriteNews(
            @RequestParam("newsId") String newsId,
            @RequestParam("userId") Long userId,
            @RequestParam("isFavorite") boolean isFavorite) {
        boolean result = newsService.favoriteNews(newsId, userId, isFavorite);
        return result ? R.ok(true) : R.fail("操作失败");
    }
    
    /**
     * 获取热门新闻
     *
     * @param limit 条数限制
     * @return 热门新闻列表
     */
    @GetMapping("/hot")
    public R<List<News>> getHotNews(
            @RequestParam(value = "limit", defaultValue = "5") int limit) {
        List<News> hotNews = newsService.getHotNews(limit);
        return R.ok(hotNews);
    }
    
    /**
     * 搜索新闻
     *
     * @param current 当前页
     * @param size 每页大小
     * @param keyword 关键词
     * @return 新闻分页列表
     */
    @GetMapping("/search")
    public R<IPage<News>> searchNews(
            @RequestParam(value = "current", defaultValue = "1") Long current,
            @RequestParam(value = "size", defaultValue = "10") Long size,
            @RequestParam("keyword") String keyword) {
        IPage<News> newsPage = newsService.searchNews(current, size, keyword);
        return R.ok(newsPage);
    }
    
    /**
     * 获取用户发布的新闻
     *
     * @param current 当前页
     * @param size 每页大小
     * @param userId 用户ID
     * @return 新闻分页列表
     */
    @GetMapping("/user/{userId}")
    public R<IPage<News>> getUserNews(
            @RequestParam(value = "current", defaultValue = "1") Long current,
            @RequestParam(value = "size", defaultValue = "10") Long size,
            @PathVariable("userId") Long userId) {
        IPage<News> newsPage = newsService.getUserNews(current, size, userId);
        return R.ok(newsPage);
    }
    
    /**
     * 获取用户收藏的新闻
     *
     * @param current 当前页
     * @param size 每页大小
     * @param userId 用户ID
     * @return 新闻分页列表
     */
    @GetMapping("/favorites/{userId}")
    public R<IPage<News>> getUserFavorites(
            @RequestParam(value = "current", defaultValue = "1") Long current,
            @RequestParam(value = "size", defaultValue = "10") Long size,
            @PathVariable("userId") Long userId) {
        IPage<News> newsPage = newsService.getUserFavorites(current, size, userId);
        return R.ok(newsPage);
    }
    
    /**
     * 将Map数据转换为News对象
     *
     * @param data Map数据
     * @return News对象
     */
    @SuppressWarnings("unchecked")
    private News convertToNews(Map<String, Object> data) {
        try {
            Map<String, Object> newsMap = (Map<String, Object>) data.get("news");
            
            News news = new News();
            if (newsMap.containsKey("title")) {
                news.setTitle((String) newsMap.get("title"));
            }
            if (newsMap.containsKey("content")) {
                news.setContent((String) newsMap.get("content"));
            }
            if (newsMap.containsKey("summary")) {
                news.setSummary((String) newsMap.get("summary"));
            }
            if (newsMap.containsKey("coverImg")) {
                news.setCoverImg((String) newsMap.get("coverImg"));
            }
            if (newsMap.containsKey("categoryId")) {
                news.setCategoryId((String) newsMap.get("categoryId"));
            }
            if (newsMap.containsKey("authorId")) {
                news.setAuthorId(Long.valueOf(newsMap.get("authorId").toString()));
            }
            if (newsMap.containsKey("status")) {
                news.setStatus(Integer.valueOf(newsMap.get("status").toString()));
            }
            
            return news;
        } catch (Exception e) {
            throw new RuntimeException("新闻数据格式错误", e);
        }
    }
    
    /**
     * 从Map数据中获取标签列表
     *
     * @param data Map数据
     * @return 标签列表
     */
    @SuppressWarnings("unchecked")
    private List<String> getTagsFromData(Map<String, Object> data) {
        try {
            return (List<String>) data.get("tags");
        } catch (Exception e) {
            return null;
        }
    }
} 